#include "Win32Device.h"

//Engine
#include "NeroGame\NGame.h"
#include "NeroEngine\NFileSystem.h"

//External
#include "CiniReader.h"

//Platform
#include "Win32Platform.h"
#include "Win32Debug.h"

//Stl
#include <stdio.h>

using namespace System;

POINT CenterWindow(int windowWidth, int windowHeight)
{
	POINT newPoint;
	newPoint.x = (GetSystemMetrics(SM_CXSCREEN) - windowWidth)/2;
	newPoint.y = (GetSystemMetrics(SM_CYSCREEN) - windowHeight)/2;
	return newPoint;
}

Win32Device::Win32Device(Win32Platform* owner, HINSTANCE instance, int showCommand)
	:mOwner(owner),
	 mInstance(instance), 
	 mShowCommand(showCommand),
	 mDevice(NULL),
	 mDeviceContext(NULL),
	 mSwapChain(NULL),
	 mRenderTargetView(NULL),
	 mDepthStencilBuffer(NULL),
	 mDepthStencilState(NULL),
	 mDepthDisabledStencilState(NULL),
	 mDepthStencilView(NULL),
	 mRasterState(NULL),
	 mAlphaDisableBlendingState(NULL),
	 mAlphaEnableBlendingState(NULL)
{
}

Win32Device::~Win32Device(void)
{
}

void Win32Device::Initialize()
{
	InitWindowHandle();
	InitD3DDevice();
}

void Win32Device::Deinitialize()
{
	if(mDevice != NULL)
	{
		mDevice->Release();
		mDevice = NULL;
	}

	if(mDeviceContext != NULL)
	{
		mDeviceContext->Release();
		mDeviceContext = NULL;
	}
	if(mSwapChain != NULL)
	{
		mSwapChain->Release();
		mSwapChain = NULL;
	}
	if(mRenderTargetView != NULL)
	{
		mRenderTargetView->Release();
		mRenderTargetView = NULL;
	}
	if(mDepthStencilBuffer != NULL)
	{
		mDepthStencilBuffer->Release();
		mDepthStencilBuffer = NULL;
	}
	if(mDepthStencilState != NULL)
	{
		mDepthStencilState->Release();
		mDepthStencilState = NULL;
	}
	if(mDepthDisabledStencilState != NULL)
	{
		mDepthDisabledStencilState->Release();
		mDepthDisabledStencilState = NULL;
	}
	if(mDepthStencilView != NULL)
	{
		mDepthStencilView->Release();
		mDepthStencilView = NULL;
	}
	if(mRasterState != NULL)
	{
		mRasterState->Release();
		mRasterState = NULL;
	}
}

void Win32Device::InitWindowHandle()
{
	WNDCLASSEX WindowDesc;
	Engine::NFileSystem fileSystem;

	CIniReader INIreader = fileSystem.LoadIni("gameconfig.ini");

	//Screen width and height set
	mScreenWidth =  INIreader.ReadInteger("Windows","Width",DefaultScreenWidth);
	mScreenHeight = INIreader.ReadInteger("Windows","Height",DefaultScreenHeight);

	mWindowTitle = INIreader.ReadString("Windows","Title","Title");
	mWindowClass = INIreader.ReadString("Windows","Class","Class");
	
	// clear out the window class for use
	ZeroMemory(&WindowDesc, sizeof(WNDCLASSEX));

    // fill in the struct with the needed information (PROBABLY DONT NEED TO SAVE)
	WindowDesc.cbSize = sizeof(WNDCLASSEX);
	WindowDesc.style = CS_HREDRAW | CS_VREDRAW | CS_NOCLOSE;
	WindowDesc.lpfnWndProc = WndProc;
	WindowDesc.cbClsExtra = NULL;
	WindowDesc.cbWndExtra = NULL;
	WindowDesc.hInstance = mInstance;
	WindowDesc.hIcon = LoadIcon(0, IDI_WINLOGO);
    WindowDesc.hCursor = LoadCursor(NULL, IDC_ARROW);
    WindowDesc.hbrBackground = (HBRUSH)COLOR_WINDOW;
	WindowDesc.lpszClassName = mWindowClass;
	
    // register the window class
    if (!RegisterClassEx(&WindowDesc))
	{
		MessageBox(NULL, "Error registering class",	"Error", MB_OK | MB_ICONERROR);
		return;
	}

    // create the window and use the result as the handle
	POINT windowLocation = CenterWindow(mScreenWidth,mScreenHeight);
	mWindowHandle = CreateWindowEx (	NULL,
										mWindowClass,            // name of the window class
										mWindowTitle,            // title of the window
										WS_OVERLAPPEDWINDOW,				// window style
										windowLocation.x,		// x-position of the window
										windowLocation.y,		// y-position of the window
										mScreenWidth,			// width of the window
										mScreenHeight,		   // height of the window
										NULL,					   // we have no parent window, NULL
										NULL,					   // we aren't using menus, NULL
										mInstance,   // application handle
										NULL	);				   // used with multiple windows, NULL
	if (!mWindowHandle)
	{
		MessageBox(NULL, "Error creating window","Error", MB_OK | MB_ICONERROR);
		return;
	}

	ShowWindow(mWindowHandle, mShowCommand); // display the window on the screen
}

void Win32Device::InitD3DDevice()
{
	// Set the feature level to DirectX 11.
	mFeatureLevel = D3D_FEATURE_LEVEL_11_0;
	//V-Sync
	mVsyncEnabled  = true;

	SetupGraphicCardInfo();
	
	SetupSwapChain();

	SetupBackBuffer();

	SetupDepthStencil();

	SetupRasterizer();

	SetupAlphaBlend();

	// Setup the projection matrix.
	float fieldOfView, screenAspect;
	fieldOfView = (float)D3DX_PI / 4.0f;
	screenAspect = (float)mScreenWidth / (float)mScreenHeight;

	// Create the projection matrix for 3D rendering.
	D3DXMatrixPerspectiveFovLH(&mProjectionMatrix, fieldOfView, screenAspect,  1000.0f, 0.1f);

	// Initialize the world matrix to the identity matrix.
	D3DXMatrixIdentity(&mWorldMatrix);

	// Create an orthographic projection matrix for 2D rendering.
	D3DXMatrixOrthoLH(&mOrthoMatrix, (float)mScreenWidth, (float)mScreenHeight, 1000.0f, 0.1f);

	// Set Render Target
	mDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
}

void Win32Device::SetupGraphicCardInfo()
{
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	
	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	NCHECK(result);

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	NCHECK(result);

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	NCHECK(result);

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	NCHECK(result);

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	NCHECK(result);

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for(i=0; i<numModes; i++)
	{
		if(displayModeList[i].Width == (unsigned int)mScreenWidth)
		{
			if(displayModeList[i].Height == (unsigned int)mScreenHeight)
			{
				mScreenNumerator = displayModeList[i].RefreshRate.Numerator;
				mScreenDenominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	NCHECK(result);

	// Store the dedicated video card memory in megabytes.
	mVideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
	wcstombs_s(&stringLength, mVideoCardDescription, 128, adapterDesc.Description, 128);
	
	// Release the display mode list.
	delete [] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Release the factory.
	factory->Release();
	factory = 0;

}

void Win32Device::SetupSwapChain()
{
	DXGI_SWAP_CHAIN_DESC scd;
	ZeroMemory(&scd, sizeof(scd));			// Initialize the swap chain description.
	
	scd.BufferCount = 1;					//Set to a single back buffer
	scd.BufferDesc.Width = mScreenWidth;
	scd.BufferDesc.Height = mScreenHeight;
	// Set the refresh rate of the back buffer.
	if(mVsyncEnabled)
	{
		scd.BufferDesc.RefreshRate.Numerator = mScreenNumerator;
		scd.BufferDesc.RefreshRate.Denominator = mScreenDenominator;
	}
	else
	{
		scd.BufferDesc.RefreshRate.Numerator = 0;
		scd.BufferDesc.RefreshRate.Denominator = 1;
	}
	scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	scd.SampleDesc.Count = 1;
	scd.SampleDesc.Quality = 0;
	scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	scd.OutputWindow = mWindowHandle;
	scd.Windowed = true;
	scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	scd.Flags = 0;


	result = D3D11CreateDeviceAndSwapChain(  NULL,
									D3D_DRIVER_TYPE_HARDWARE, 
									NULL, 
									0, 
									&mFeatureLevel, 
									1, 
									D3D11_SDK_VERSION,
									&scd,
									&mSwapChain,
									&mDevice,
									NULL,
									&mDeviceContext);
	NCHECK(result);

	ID3D11Texture2D* backBuffer = NULL;
	mSwapChain->GetBuffer(0, _uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer);

	result = mDevice->CreateRenderTargetView(backBuffer, NULL, &mRenderTargetView);
	NCHECK(result);

	backBuffer->Release();
	backBuffer = 0;
}

void Win32Device::SetupBackBuffer()
{
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	// Initialize the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = mScreenWidth;
	depthBufferDesc.Height = mScreenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// Create the texture for the depth buffer using the filled out description.
	result = mDevice->CreateTexture2D(&depthBufferDesc, NULL, &mDepthStencilBuffer);
	NCHECK(result);
}

void Win32Device::SetupDepthStencil()
{
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;

	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	result = mDevice->CreateDepthStencilState(&depthStencilDesc, &mDepthStencilState);
	NCHECK(result);

	// Set the depth stencil state.
	mDeviceContext->OMSetDepthStencilState(mDepthStencilState, 1);


	D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
	// Clear the second depth stencil state before setting the parameters.
	ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

	// Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is 
	// that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
	depthDisabledStencilDesc.DepthEnable = false;
	depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthDisabledStencilDesc.StencilEnable = true;
	depthDisabledStencilDesc.StencilReadMask = 0xFF;
	depthDisabledStencilDesc.StencilWriteMask = 0xFF;
	depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the state using the device.
	result = mDevice->CreateDepthStencilState(&depthDisabledStencilDesc, &mDepthDisabledStencilState);
	NCHECK(result);

	// Initailze the depth stencil view.
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = mDevice->CreateDepthStencilView(mDepthStencilBuffer, &depthStencilViewDesc, &mDepthStencilView);
	NCHECK(result);
}

void Win32Device::SetupRasterizer()
{
	// Setup the raster description which will determine how and what polygons will be drawn.
	D3D11_RASTERIZER_DESC rasterDesc;
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = mDevice->CreateRasterizerState(&rasterDesc, &mRasterState);
	NCHECK(result);

	// Now set the rasterizer state.
	mDeviceContext->RSSetState(mRasterState);

	// Setup the viewport for rendering.
	D3D11_VIEWPORT viewport;
	viewport.Width = (float)mScreenWidth;
	viewport.Height = (float)mScreenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	mDeviceContext->RSSetViewports(1, &viewport);
}

void Win32Device::SetupAlphaBlend()
{
	D3D11_BLEND_DESC blendStateDescription;
	// Clear the blend state description.
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

	// Create an alpha enabled blend state description.

	// Create an alpha enabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
	blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

	// Create the blend state using the description.
	result = mDevice->CreateBlendState(&blendStateDescription, &mAlphaEnableBlendingState);
	NCHECK(result);

	// Modify the description to create an alpha disabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
	// Create the blend state using the description.
	result = mDevice->CreateBlendState(&blendStateDescription, &mAlphaDisableBlendingState);
	NCHECK(result);
}

ID3D11Device* Win32Device::GetDevice()
{
	return mDevice;
}

ID3D11DeviceContext* Win32Device::GetDeviceContext()
{
	return mDeviceContext;
}

ID3D11RenderTargetView* Win32Device::GetRTVeiw()
{ 
	return mRenderTargetView;
}

ID3D11DepthStencilView* Win32Device::GetDSV()
{ 
	return mDepthStencilView;
}

void Win32Device::SetBackBufferRenderTarget()
{
	// Bind the render target view and depth stencil buffer to the output render pipeline.
	mDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
}

IDXGISwapChain* Win32Device::GetSwapChain()
{ 
	return mSwapChain;
}

bool Win32Device::VsyncEnabled()
{ 
	return mVsyncEnabled;
}

void Win32Device::TurnZBufferOn()
{
	mDeviceContext->OMSetDepthStencilState(mDepthStencilState, 1);
}
	
void Win32Device::TurnZBufferOff()
{
	mDeviceContext->OMSetDepthStencilState(mDepthDisabledStencilState, 1);
}

void Win32Device::TurnOnAlphaBlending()
{
	float blendFactor[4];
	
	// Setup the blend factor.
	blendFactor[0] = 0.0f;
	blendFactor[1] = 0.0f;
	blendFactor[2] = 0.0f;
	blendFactor[3] = 0.0f;
	
	// Turn on the alpha blending.
	mDeviceContext->OMSetBlendState(mAlphaEnableBlendingState, blendFactor, 0xffffffff);

	return;
}

void Win32Device::TurnOffAlphaBlending()
{
	float blendFactor[4];
	

	// Setup the blend factor.
	blendFactor[0] = 0.0f;
	blendFactor[1] = 0.0f;
	blendFactor[2] = 0.0f;
	blendFactor[3] = 0.0f;
	
	// Turn off the alpha blending.
	mDeviceContext->OMSetBlendState(mAlphaDisableBlendingState, blendFactor, 0xffffffff);

	return;
}

int Win32Device::GetScreenHeight()
{
	return mScreenHeight;
}

int Win32Device::GetScreenWidth()
{
	return mScreenWidth;
}

D3DXMATRIX& Win32Device::GetWorldMatrix()
{ 
	return mWorldMatrix;
}

D3DXMATRIX& Win32Device::GetProjectionMatrix() 
{ 
	return mProjectionMatrix;
}

D3DXMATRIX& Win32Device::GetOrthMatrix() 
{ 
	return mOrthoMatrix;
}

LRESULT CALLBACK Win32Device::WndProc(HWND windowHandle, UINT message, WPARAM wParam,LPARAM lParam)
{
    switch(message)	// sort through and find what code to run for the message given
    {
        case WM_DESTROY: // this message is read when the window is closed  
			GetGame()->EndGame();
			PostQuitMessage(0); // close the application entirely
			break;
		case WM_SETFOCUS:
			break;
		case WM_KEYDOWN:
		
			break;
		case WM_MOUSEMOVE:
			
			break;
		case WM_LBUTTONDOWN:
		case WM_RBUTTONDOWN:
		case WM_MBUTTONDOWN:
			
			break;

		case WM_ENTERSIZEMOVE:
			break;

		case WM_ENTERMENULOOP:
			break;

		case WM_SETCURSOR:
			
			break;
    }
    return DefWindowProc (windowHandle, message, wParam, lParam); // Handle any messages the switch statement didn't
}